import sys
from PySide2.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np
from tools.MatplotlibChartsTools.BarChartTools import BarChartTools


class MatplotlibChartsTools(QMainWindow):
    """
    matplotlib: 图形
    """

    def draw_bar_chart(self):
        """
        绘制柱状图
        :return:
        """
        layout = QVBoxLayout(self.central_widget)
        fig = Figure()
        # 单个子图
        ax = fig.add_subplot(111)
        bars = ax.bar(range(5), np.random.rand(5))

        canvas = FigureCanvas(fig)
        canvas.draw()
        layout.addWidget(canvas)
        # pass



    def __init__(self):
        super().__init__()

        # 设置中心部件和布局
        self.central_widget = QWidget(self)
        self.setCentralWidget(self.central_widget)
        layout = QVBoxLayout(self.central_widget)

        # 创建 matplotlib 图形
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        # a = self.draw_bar_chart()
        # layout.addWidget(self.canvas)

        # 添加子图和绘制数据
        self.ax = self.fig.add_subplot(111)
        self.bars = self.ax.bar(['A', 'B', 'C', 'D'],
                                [23, 45, 56, 78])  # 保存柱子引用以便后续更新

        # 初始化颜色数组（用于跟踪当前颜色状态）
        self.colors = ['b', 'g', 'r', 'c', 'm']  # 初始颜色

        # 刷新画布
        # self.canvas.draw()

        # 连接点击事件
        self.canvas.mpl_connect('button_press_event', self.on_click)
        layout.addWidget(self.canvas)

    def abc(self):
        # 创建 matplotlib 图形
        fig = Figure()
        canvas = FigureCanvas(fig)
        # a = self.draw_bar_chart()
        # layout.addWidget(self.canvas)

        # 添加子图和绘制数据
        ax = fig.add_subplot(111)
        bars = ax.bar(range(5), np.random.rand(5))  # 保存柱子引用以便后续更新

        # 初始化颜色数组（用于跟踪当前颜色状态）
        colors = ['b', 'g', 'r', 'c', 'm']  # 初始颜色

        return canvas
    def on_click(self, event):
        if event.inaxes is None:
            return

            # 获取点击位置的 x 坐标
        x_click = event.xdata
        print(event)
        print(self.bars[0])
        print(self.bars[0].get_x())
        print(self.bars[0].get_width())


        # 遍历所有柱子，找到被点击的柱子
        for bar, color in zip(self.bars, self.colors):
            # 这里我们简单地假设点击在柱子的中心位置左右
            if np.abs(bar.get_x() + bar.get_width() / 2 - x_click) < bar.get_width() / 2:
                # 切换颜色（这里简单地在几种颜色之间循环）
                new_color = 'b' if color == 'r' else 'r'  # 示例：红蓝切换
                self.colors[self.bars.index(bar)] = new_color
                bar.set_color(new_color)
                self.canvas.draw_idle()  # 仅在必要时更新画布
                break


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_win = MatplotlibChartsTools()
    main_win.show()
    sys.exit(app.exec_())
